package com.app.controller;

import com.app.mapper.QuestionnaireInvestigationMapper;
import com.app.model.*;
import com.app.service.*;
import com.app.util.*;
import com.app.vo.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Description:调查问卷
 * @Author: N
 * @Date: 2022/10/29 15:26
 */
@RestController
@RequestMapping("/")
public class QuestionnaireInvestigationController {
    @Autowired
    QuestionnaireInvestigationService questionnaireInvestigationService;
    @Autowired
    ConfigService configService;
    @Autowired
    AdminUserService adminUserService;
    @Autowired
    QuestionnaireHelpService questionnaireHelpService;

    @Autowired
    HelpRecordService helpRecordService;

    @Autowired
    QuestionnaireInvestigationMapper questionnaireInvestigationMapper;

    @PostMapping("/addQuestionnaireInvestigation")
    public Result<Object> getAttentionList(QuestionnaireInvestigationModel model) {
        QuestionnaireInvestigationModel questionnaireInvestigationModel = questionnaireInvestigationService.getModelByIdCard(model.getIdCard());
        if(questionnaireInvestigationModel!=null)
        {
            return Result.error(406,"您提交的信息已存在，请勿重复提交");
        }else{
            model.setCrtTime(CommonHelp.getNowTimestamp());
            questionnaireInvestigationService.insert(model);
            return Result.success("操作成功");
        }
    }
    @PostMapping("/addQuestionnaireInvestigationBack")
    public Result<Object> addQuestionnaireInvestigationBack( @RequestBody QuestionnaireInvestigationModel model) {
        QuestionnaireInvestigationModel questionnaireInvestigationModel = questionnaireInvestigationService.getModelByIdCard(model.getIdCard());
        if(questionnaireInvestigationModel!=null)
        {
            return Result.error(406,"您提交的信息已存在，请勿重复提交");
        }else{
            model.setCrtTime(CommonHelp.getNowTimestamp());
            questionnaireInvestigationService.insert(model);
            return Result.success("操作成功");
        }
    }


    /**
     * 问卷调查列表
     */
    @GetMapping("/getQuestionnaireInvestigationList")
    @ResponseBody
    public Result<Object> getQuestionnaireInvestigationList(HttpServletRequest request,QuestionnaireInvestigationModel model) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405, "token不存在");
        }

        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        model.setUserGroupId(user.getGroupId());
        Page<QuestionnaireInvestigationModel> modelPage = questionnaireInvestigationService.modelPage(model);
        QuestionnaireInvestigationVo vo = new QuestionnaireInvestigationVo();
        vo.setList(modelPage.getRecords());
        vo.setCount((int) modelPage.getTotal());
        return Result.success(vo);
    }
    /**
     * 问卷调查d(单个)
     */
    @GetMapping("/getQuestionnaireInvestigationById")
    @ResponseBody
    public Result<Object> getQuestionnaireInvestigationById(HttpServletRequest request,Integer id) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405, "token不存在");
        }
        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        return Result.success(questionnaireInvestigationService.getModelById(id));
    }

    @PostMapping({"/getQuestionnaireInvestigationTables"})
    @ResponseBody
    public void getQuestionnaireInvestigationTables(HttpServletRequest request,HttpServletResponse response, QuestionnaireInvestigationModel model) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        assert userId != null;
        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        model.setUserGroupId(user.getGroupId());
        model.setPage(1);
        model.setLimit(999999);
        Page<QuestionnaireInvestigationModel> modelPage = this.questionnaireInvestigationService.modelPage(model);
        QuestionnaireInvestigationVo vo = new QuestionnaireInvestigationVo();
        vo.setList(modelPage.getRecords());
        vo.setCount((int) modelPage.getTotal());
        Map map = Maps.newHashMap();
        map.put("list", vo.getList());
        ClassPathResource classPathResource;
        if(user.getUserType().equals(3))
        {
            classPathResource = new ClassPathResource("C:/upload/questionnaire_investigation_tables.xlsx");
        }else {
            classPathResource = new ClassPathResource("C:/upload/questionnaire_investigation_tables_2.xlsx");
        }
        String path = classPathResource.getPath();
        TemplateExportParams templateExportParams1 = new TemplateExportParams(path);
        Workbook wb = ExcelExportUtil.exportExcel(templateExportParams1, map);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
        String fileName = "问卷调查" + time + ".xlsx";
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 导出问卷调查列表
     */
    @PostMapping("/getQuestionnaireInvestigationStatistics")
    @ResponseBody
    public void getQuestionnaireInvestigationStatistics(HttpServletRequest request,HttpServletResponse response, QuestionnaireInvestigationModel model) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        assert userId != null;
        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        model.setUserGroupId(user.getGroupId());
        model.setPage(1);
        model.setLimit(999999);
        Page<QuestionnaireInvestigationModel> modelPage = questionnaireInvestigationService.modelPage(model);
        List<QuestionnaireInvestigationStatisticsVo> voList = new ArrayList<>();
        List<QuestionnaireInvestigationModel> list = modelPage.getRecords();
        List<ConfigModel> townshipList = configService.getGroupListById(user.getGroupId());
        int count = 0;
        for (ConfigModel configModel : townshipList) {
            QuestionnaireInvestigationStatisticsVo vo = new QuestionnaireInvestigationStatisticsVo();
            vo.setId(count++);
            vo.setTownship(configModel.getName());
            int maleCount = 0;//男数量
            int thirtyCount = 0;
            int femaleCount = 0;//女总数
            String femalePercentage;//女占比
            String thirtyPercentage;//30一下占比
            int fortyCount = 0;//31-40一下数
            String fortyPercentage;//31-40一下占比
            int fiftyCount = 0;//41-50一下数
            String fiftyPercentage;//41-50一下占比
            int sixtyCount = 0;//51-60一下数
            String sixtyPercentage;//51-60一下占比
            int middleSchoolCount = 0;//初中以下数
            String middleSchoolPercentage;//初中以下下占比
            int highSchoolCount = 0;//高中以下数
            String highSchoolPercentage;//高中以下占比
            int universityCount = 0;//大学以上数
            String universityPercentage;//大学以上占比
            int workingCount = 0;//打工数
            String workingPercentage;//打工占比
            int farmerCount = 0;//务农数
            String farmerPercentage;//务农占比
            int trainCount = 0;//培训意愿数
            String trainPercentage;//培训意愿占比
            int total = 0;
            for (QuestionnaireInvestigationModel questionnaireInvestigationModel : list) {
                if(questionnaireInvestigationModel.getGroupId().contains(configModel.getId().toString()))
                {
                    total++;
                }
                vo.setTotal(total);
                if (questionnaireInvestigationModel.getGroupId().contains(configModel.getId().toString())&&questionnaireInvestigationModel.getSex().equals(1)) {
                    maleCount++;
                }
                if (questionnaireInvestigationModel.getGroupId().contains(configModel.getId().toString())&&questionnaireInvestigationModel.getSex().equals(2)) {
                    femaleCount++;
                }
                if (questionnaireInvestigationModel.getGroupId().contains(configModel.getId().toString())&&questionnaireInvestigationModel.getAge() < 30) {
                    thirtyCount++;
                }
                if (questionnaireInvestigationModel.getGroupId().contains(configModel.getId().toString())&&questionnaireInvestigationModel.getAge() > 30 && questionnaireInvestigationModel.getAge() < 40) {
                    fortyCount++;
                }
                if (questionnaireInvestigationModel.getGroupId().contains(configModel.getId().toString())&&questionnaireInvestigationModel.getAge() > 40 && questionnaireInvestigationModel.getAge() < 50) {
                    fiftyCount++;
                }
                if (questionnaireInvestigationModel.getGroupId().contains(configModel.getId().toString())&&questionnaireInvestigationModel.getAge() > 50 && questionnaireInvestigationModel.getAge() < 60) {
                    sixtyCount++;
                }
                if (questionnaireInvestigationModel.getGroupId().contains(configModel.getId().toString())&&questionnaireInvestigationModel.getEducationId() <= 2) {
                    middleSchoolCount++;
                }
                if (questionnaireInvestigationModel.getGroupId().contains(configModel.getId().toString())&&questionnaireInvestigationModel.getEducationId() == 2) {
                    highSchoolCount++;
                }
                if (questionnaireInvestigationModel.getGroupId().contains(configModel.getId().toString())&&questionnaireInvestigationModel.getEducationId() >= 4) {
                    universityCount++;
                }
                if(questionnaireInvestigationModel.getPracticeState()!=null)
                {
                    if (questionnaireInvestigationModel.getGroupId().contains(configModel.getId().toString())&&questionnaireInvestigationModel.getPracticeState().equals(1)) {
                        farmerCount++;
                    }
                    if (questionnaireInvestigationModel.getGroupId().contains(configModel.getId().toString())&&questionnaireInvestigationModel.getPracticeState().equals(2)) {
                        workingCount++;
                    }
                }

                if (questionnaireInvestigationModel.getGroupId().contains(configModel.getId().toString())&&questionnaireInvestigationModel.getWhetherTrain().equals(1)) {
                    trainCount++;
                }


            }
            vo.setMaleCount(maleCount);
            String malePercentage = CalculateUtil.CalculateUtil(BigDecimal.valueOf(maleCount), BigDecimal.valueOf(total));//男百分比
            vo.setMalePercentage(malePercentage);
            vo.setFemaleCount(femaleCount);//
            femalePercentage = CalculateUtil.CalculateUtil(BigDecimal.valueOf(femaleCount), BigDecimal.valueOf(total));//女百分比
            vo.setFemalePercentage(femalePercentage);
            vo.setThirtyCount(thirtyCount);
            thirtyPercentage = CalculateUtil.CalculateUtil(BigDecimal.valueOf(thirtyCount), BigDecimal.valueOf(total));//30以下
            vo.setThirtyPercentage(thirtyPercentage);
            vo.setFortyCount(fortyCount);
            fortyPercentage = CalculateUtil.CalculateUtil(BigDecimal.valueOf(fortyCount), BigDecimal.valueOf(total));
            vo.setFortyPercentage(fortyPercentage);
            vo.setFiftyCount(fiftyCount);
            fiftyPercentage = CalculateUtil.CalculateUtil(BigDecimal.valueOf(fiftyCount), BigDecimal.valueOf(total));
            vo.setFiftyPercentage(fiftyPercentage);
            vo.setSixtyCount(sixtyCount);
            sixtyPercentage = CalculateUtil.CalculateUtil(BigDecimal.valueOf(sixtyCount), BigDecimal.valueOf(total));
            vo.setSixtyPercentage(sixtyPercentage);
            vo.setMiddleSchoolCount(middleSchoolCount);
            middleSchoolPercentage = CalculateUtil.CalculateUtil(BigDecimal.valueOf(middleSchoolCount), BigDecimal.valueOf(total));
            vo.setMiddleSchoolPercentage(middleSchoolPercentage);
            vo.setHighSchoolCount(highSchoolCount);
            highSchoolPercentage = CalculateUtil.CalculateUtil(BigDecimal.valueOf(highSchoolCount), BigDecimal.valueOf(total));
            vo.setHighSchoolPercentage(highSchoolPercentage);
            vo.setUniversityCount(universityCount);
            universityPercentage = CalculateUtil.CalculateUtil(BigDecimal.valueOf(universityCount), BigDecimal.valueOf(total));
            vo.setUniversityPercentage(universityPercentage);
            vo.setFarmerCount(farmerCount);
            farmerPercentage = CalculateUtil.CalculateUtil(BigDecimal.valueOf(farmerCount), BigDecimal.valueOf(total));
            vo.setFarmerPercentage(farmerPercentage);
            vo.setWorkingCount(workingCount);
            workingPercentage = CalculateUtil.CalculateUtil(BigDecimal.valueOf(workingCount), BigDecimal.valueOf(total));
            vo.setWorkingPercentage(workingPercentage);
            vo.setTrainCount(trainCount);
            trainPercentage = CalculateUtil.CalculateUtil(BigDecimal.valueOf(trainCount), BigDecimal.valueOf(total));
            vo.setTrainPercentage(trainPercentage);
            voList.add(vo);
        }
        Map map = Maps.newHashMap();
        map.put("list", voList);
        //获取导出模板地址
        ClassPathResource classPathResource = new ClassPathResource("C:/upload/questionnaire_investigation_statistics.xlsx");
        String path = classPathResource.getPath();
        TemplateExportParams templateExportParams1 = new TemplateExportParams(path);
        Workbook wb = ExcelExportUtil.exportExcel(templateExportParams1, map);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
        String fileName = "资源摸底调查汇总表" + time + ".xlsx";
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    /**
     * 问卷调查列表
     */
    @GetMapping("/getHelpList")
    @ResponseBody
    public Result<Object> getHelpList(HttpServletRequest request, QuestionnaireHelpModel model) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405, "token不存在");
        }

        QuestionnaireHelpVo vo = questionnaireHelpService.getModelByPage(model);
        return Result.success(vo);
    }

    /**
     * 删除帮扶记录
     */
    @GetMapping("/delHelp")
    @ResponseBody
    public Result<Object> delHelp(HttpServletRequest request, Integer id,Integer questId) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405, "token不存在");
        }
        questionnaireHelpService.delete(id);
        List<QuestionnaireHelpModel> list = questionnaireHelpService.getModelByUserId(questId);
        if(list==null||list.size()==0)
        {
            QuestionnaireInvestigationModel questionnaireInvestigationModel = questionnaireInvestigationService.getModelById(questId);
            questionnaireInvestigationModel.setIsHelp(0);
            questionnaireInvestigationService.update(questionnaireInvestigationModel);
        }
        return Result.success("操作成功");
    }

    @PostMapping("/addHelp")
    public Result<Object> addHelp(@RequestBody QuestionnaireHelpModel model) {
        QuestionnaireInvestigationModel questionnaireInvestigationModel = questionnaireInvestigationService.getModelById(model.getUserId());
        questionnaireInvestigationModel.setIsHelp(1);
        if(model.getState()==2)
        {
            questionnaireInvestigationModel.setIsWork(1);
        }
        questionnaireInvestigationService.update(questionnaireInvestigationModel);
        model.setCrtTime(String.valueOf(CommonHelp.getNowTimestamp()));
        questionnaireHelpService.insert(model);
        return Result.success("操作成功");
    }
    @PostMapping("/getWorkGo")
    public Result<Object> getWorkGo(@RequestBody QuestionnaireHelpModel model) {
        QuestionnaireHelpModel questionnaireInvestigationModel = questionnaireHelpService.getModel(model);
        return Result.success(questionnaireInvestigationModel);
    }

    @PostMapping("/editIsWork")
    public Result<Object> editIsWork(@RequestBody QuestionnaireInvestigationModel model) {
        Integer isWork = model.getIsWork();
        QuestionnaireInvestigationModel questionnaireInvestigationModel = questionnaireInvestigationService.getModelById(model.getId());
        questionnaireInvestigationModel.setIsWork(isWork);
        if(isWork.equals(1))
        {
            questionnaireInvestigationModel.setWorkTime(String.valueOf(CommonHelp.getNowTimestamp()));
        }
        questionnaireInvestigationService.update(questionnaireInvestigationModel);
        return Result.success("操作成功");
    }

    @PostMapping("/importQuest")
    public void importExcel(@RequestParam("file") MultipartFile file) {
        questionnaireInvestigationService.importData(file);
    }

    /**
     * 零时脚本
     */
    @GetMapping("/doHelpRecord")
    @ResponseBody
    public Result<Object> doHelpRecord() {
        List<QuestionnaireInvestigationModel> list = questionnaireInvestigationService.getHelpModelList();
        Map<Object,String> typeMap = new HashMap<>();
        typeMap.put(1,"短信推荐");
        typeMap.put(2,"平台推荐");
        typeMap.put(3,"微信模板消息推荐");
        Map<Object,String> typeMap2 = new HashMap<>();
        typeMap2.put(1,"岗位");
        typeMap2.put(2,"招聘会");
        typeMap2.put(3,"培训");
        for (int i = 0; i < list.size(); i++) {
            HelpRecordModel model = new HelpRecordModel();
            model.setRealName(list.get(i).getRealName());
            model.setUserId(list.get(i).getId());
            int[] arr = generateRandomNumbers(3, 3);
            int[] arr2 = generateRandomNumbers(3, 3);
            model.setOneHelp(typeMap.get(arr[0])+typeMap2.get(arr2[0]));
            model.setTwoHelp(typeMap.get(arr[1])+typeMap2.get(arr2[1]));
            model.setThreeHelp(typeMap.get(arr[2])+typeMap2.get(arr2[2]));
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date randomDate = randomDate("2023-08-01", "2023-09-11");
            String dateOne = format.format(randomDate);
            Date randomDate2 = randomDate(dateOne, "2023-09-11");
            String date2 = format.format(randomDate2);
            Date randomDate3 = randomDate(date2, "2023-09-11");
            String date3 = format.format(randomDate3);
            model.setOneHelpTime(dateOne);
            model.setTwoHelpTime(date2);
            model.setThreeHelpTime(date3);
            helpRecordService.insert(model);

        }
        return Result.success("操作成功");
    }

    /**
     * 查询平台帮扶记录
     */
    @GetMapping("/getHelpRecordList")
    @ResponseBody
    public Result<Object> getHelpRecordList(HttpServletRequest request, HelpRecordModel model) {
        HelpRecordVo vo = new HelpRecordVo();
        if (model.getType() == 1) {
            vo = helpRecordService.getAllList(model);
        } else {
            List<HelpRecordModel> list = vo.getList();
            List<QuestionnaireInvestigationModel> questionnaireInvestigationModels = questionnaireInvestigationMapper.getModelByHelpList();
            for (int i = 0; i < questionnaireInvestigationModels.size(); i++) {
                HelpRecordModel helpRecordModel = new HelpRecordModel();
                helpRecordModel.setRealName(questionnaireInvestigationModels.get(i).getRealName());
                if (questionnaireInvestigationModels.get(i).getWishWorkTypeId() != null && questionnaireInvestigationModels.get(i).getWishWorkTypeId() > 0) {
                    ConfigModel configModel = configService.getModelById(questionnaireInvestigationModels.get(i).getWishWorkTypeId());
                    helpRecordModel.setWishWorkTypeId(configModel.getName());
                }
                helpRecordModel.setOneHelpTime(questionnaireInvestigationModels.get(i).getCrtTime().toString());
                helpRecordModel.setOneHelp(questionnaireInvestigationModels.get(i).getContent());
                helpRecordModel.setHelpTypeText("线下");
                list.add(helpRecordModel);
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setOneHelpTime(format.format(Timestamp.valueOf(list.get(i).getOneHelpTime())));
                list.get(i).setTwoHelpTime(format.format(Timestamp.valueOf(list.get(i).getTwoHelpTime())));
                list.get(i).setThreeHelpTime(format.format(Timestamp.valueOf(list.get(i).getThreeHelpTime())));
            }
            vo.setList(list);
        }
        //对信息进行脱敏返回
        List<HelpRecordModel> helpRecordList = vo.getList();
        if (CollectionUtils.isNotEmpty(helpRecordList)){
            for (HelpRecordModel helpRecord : helpRecordList) {
                String realName = DateMaskingUtils.chineseName(helpRecord.getRealName());//脱敏后的姓名
                helpRecord.setRealName(realName);
            }
        }
        return Result.success(vo);
    }
    /**
     * 问卷调查列表
     */
    @GetMapping("/getQuestionnaireInvestigationTwoList")
    @ResponseBody
    public Result<Object> getQuestionnaireInvestigationTwoList(HttpServletRequest request, QuestionnaireInvestigationModel model) {
        Page<QuestionnaireInvestigationModel> modelPage = questionnaireInvestigationService.modelPage(model);
        QuestionnaireInvestigationVo vo = new QuestionnaireInvestigationVo();
        vo.setList(modelPage.getRecords());
        vo.setCount((int) modelPage.getTotal());
        return Result.success(vo);
    }
    public static int[] generateRandomNumbers(int n, int max) {
        if (n > max) {
            throw new IllegalArgumentException("n must be less than or equal to max");
        }

        int[] arr = new int[n];
        Random random = new Random();

        for (int i = 0; i < n; i++) {
            int num;
            do {
                num = random.nextInt(max) + 1;
            } while (contains(arr, num));
            arr[i] = num;
        }

        return arr;
    }
    private static boolean contains(int[] arr, int num) {
        for (int i : arr) {
            if (i == num) {
                return true;
            }
        }
        return false;
    }

    /**

     * 生成随机时间

     *

     * @param beginDate

     * @param endDate

     * @return

     */

    public static Date randomDate(String beginDate, String endDate) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

            Date start = format.parse(beginDate);// 构造开始日期

            Date end = format.parse(endDate);// 构造结束日期

// getTime()表示返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。

            if (start.getTime() >= end.getTime()) {
                return null;

            }

            long date = random(start.getTime(), end.getTime());

            return new Date(date);

        } catch (Exception e) {
            e.printStackTrace();

        }

        return null;

    }

    public static long random(long begin, long end) {
        long rtn = begin + (long) (Math.random() * (end - begin));

// 如果返回的是开始时间和结束时间，则递归调用本函数查找随机值

        if (rtn == begin || rtn == end) {
            return random(begin, end);

        }

        return rtn;

    }

    public static void main(String[] args) {
        Date randomDate = randomDate("2023-08-01", "2023-09-11");

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        String result = format.format(randomDate);

        System.out.println(result);

    }

}
